// 收货中心逻辑
Page({
  data: {
    form: {
      productDate: '',
      mpn: '',
      // manufacturer/mediacode 改为使用 jpn 同 MPn 以及 logo 字段
      logo: 'YAGEO',
      rohs: true,
      lot: '',
      dc: '',
      count: 1,
      qty: 0,
      autoSubmit: true,
    },
    scanValue: '',
    badges: { basic: false, poData: false, mpn: false, label: 0 },
    items: [],
    apiKey: 'sk-1b39ca0da77b49978e743677464408b3',
    rawText: '',
    parsed: null,
    _latestImagePath: ''
  },

  /**
   * 将 OCR/模型返回的 JSON 结构标准化为内部表单字段
   * 支持以下来源键：
   * - DATE -> form.productDate (YYYY-MM-DD 格式化)
   * - OUR_P/N -> form.mpn
   * - ROHS_Y(C) -> form.rohs (Y/Yes/True 视为 true)
   * - INSPECTION/LOT_NO -> form.lot
   * - QTY -> form.qty (数字)
   * 兼容老的字段：datacode/logo/jpn/mpn/qty
   */
  _normalizeParsedToForm(parsed) {
    if (!parsed || typeof parsed !== 'object') return null
    const result = {}

    // 1) 生产日期：优先 DATE；若形如 20181122 -> 2018-11-22
    const rawDate = parsed.DATE || parsed.date || parsed.datacode || ''
    if (rawDate) {
      const s = String(rawDate).replace(/[^0-9]/g, '')
      if (s.length === 8) {
        result.productDate = `${s.slice(0,4)}-${s.slice(4,6)}-${s.slice(6,8)}`
      } else if (/^\d{4}-\d{2}-\d{2}$/.test(String(rawDate))) {
        result.productDate = String(rawDate)
      }
    }

    // 2) MPN：OUR_P/N 或 MPN 或 mpn
    if (parsed['OUR_P/N']) result.mpn = String(parsed['OUR_P/N']).trim()
    else if (parsed.MPN) result.mpn = String(parsed.MPN).trim()
    else if (parsed.mpn) result.mpn = String(parsed.mpn).trim()

    // 3) ROHS：ROHS_Y(C) / ROHS_Compliant / Halogen_Free / rohs -> 布尔
    const rohsRaw =
      parsed['ROHS_Y(C)'] != null ? parsed['ROHS_Y(C)'] :
      (parsed.ROHS_Compliant != null ? parsed.ROHS_Compliant :
      (parsed.Halogen_Free != null ? parsed.Halogen_Free : parsed.rohs))
    if (rohsRaw != null) {
      const text = String(rohsRaw).toLowerCase()
      result.rohs = /(y|yes|true|1)/.test(text)
    }

    // 4) LOT：INSPECTION/LOT_NO 或 lot
    if (parsed['INSPECTION/LOT_NO']) result.lot = String(parsed['INSPECTION/LOT_NO']).trim()
    else if (parsed.lot) result.lot = String(parsed.lot).trim()

    // 5) QTY
    const qtyRaw = parsed.QTY != null ? parsed.QTY : parsed.qty
    if (qtyRaw != null && qtyRaw !== '') {
      const n = Number(String(qtyRaw).replace(/[^0-9.-]/g, ''))
      result.qty = isNaN(n) ? 0 : n
    }

    // 6) logo 固定为 YAGEO
    result.logo = 'YAGEO'

    // 7) DC：优先 DC 字段，否则 datacode（去非数字）。DC 即为 DateCode
    if (parsed.DC != null) {
      result.dc = String(parsed.DC).trim()
    } else if (parsed.datacode) {
      const dcStr = String(parsed.datacode).replace(/[^0-9]/g, '')
      if (dcStr.length >= 2) result.dc = dcStr
    }

    return result
  },

  onLoad() {
    // 载入 OCR 页面保存的 API-KEY
    try {
      const saved = wx.getStorageSync('dashscope_api_key') || ''
      if (saved) this.setData({ apiKey: saved })
    } catch (e) {}
  },

  onDateChange(e) {
    this.setData({ 'form.productDate': e.detail.value })
  },
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    if (!field) return
    this.setData({ [`form.${field}`]: value })
  },
  onToggleRohs() {
    this.setData({ 'form.rohs': !this.data.form.rohs })
  },
  onAutoSubmitChange(e) {
    this.setData({ 'form.autoSubmit': e.detail.value })
  },

  // 点击“请扫描信息”：使用系统相机拍照并上传到 OCR
  onScanInputTap() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: async (res) => {
        const imgPath = (res.tempFilePaths && res.tempFilePaths[0]) || (res.tempFiles && res.tempFiles[0] && res.tempFiles[0].path)
        if (!imgPath) {
          wx.showToast({ title: '未获取到照片', icon: 'none' })
          return
        }
        this.setData({ _latestImagePath: imgPath })

        wx.showLoading({ title: '识别中', mask: true })
        try {
          const pretty = await this._runDashOCRWithImage(imgPath)
          this.setData({ rawText: pretty })

          let parsed = this.data.parsed
          if (!parsed) {
            try { parsed = JSON.parse(pretty) } catch (_) {
              parsed = this._extractJsonFromText(pretty)
            }
          }
          if (parsed && typeof parsed === 'object') {
            const patch = this._normalizeParsedToForm(parsed) || {}
            var nextForm = Object.assign({}, this.data.form, patch)
            this.setData({ form: nextForm, parsed: parsed })
          }
        } catch (e) {
          wx.showToast({ title: '识别失败', icon: 'none' })
        } finally {
          wx.hideLoading()
        }
      },
      fail: () => {
        // 用户取消或失败，不处理
      }
    })
  },


  _handleScanResult(value) {
    // 写入本地日志存储
    const scanLogs = wx.getStorageSync('scanLogs') || []
    const nowTs = Date.now()
    scanLogs.unshift({ ts: nowTs, value, type: 'single', charLen: String(value || '').length })
    if (scanLogs.length > 200) scanLogs.length = 200
    wx.setStorageSync('scanLogs', scanLogs)

    this.setData({ scanValue: value })
    this._afterScan(value)
  },

  _loadImageToCanvas(path) {
    return new Promise((resolve, reject) => {
      const query = wx.createSelectorQuery()
      // 已移除隐藏 canvas，不再支持本地二维码解析
      reject(new Error('canvas removed'))
    })
  },

  async _decodeQrFromImage(path) {
    // 本页面已不再解析 QR，仅保留 OCR 流程
    return null
  },

  _readFileAsDataUrl(filePath) {
    const fs = wx.getFileSystemManager()
    const ext = (filePath.split('.').pop() || '').toLowerCase()
    const mime = ext === 'png' ? 'image/png' : (ext === 'webp' ? 'image/webp' : (ext === 'bmp' ? 'image/bmp' : 'image/jpeg'))
    return new Promise((resolve, reject) => {
      fs.readFile({
        filePath,
        encoding: 'base64',
        success: (res) => resolve(`data:${mime};base64,${res.data}`),
        fail: reject,
      })
    })
  },

  _extractJsonFromText(text) {
    if (!text || typeof text !== 'string') return null
    try { return JSON.parse(text) } catch (e) {}
    const codeBlockMatch = text.match(/```json[\s\S]*?```/i) || text.match(/```[\s\S]*?```/)
    if (codeBlockMatch && codeBlockMatch[0]) {
      const inner = codeBlockMatch[0].replace(/```json/i, '').replace(/```/g, '').trim()
      try { return JSON.parse(inner) } catch (e) {}
    }
    const firstBrace = text.indexOf('{')
    const lastBrace = text.lastIndexOf('}')
    if (firstBrace >= 0 && lastBrace > firstBrace) {
      const maybe = text.slice(firstBrace, lastBrace + 1)
      try { return JSON.parse(maybe) } catch (e) {}
    }
    return null
  },

  async _runDashOCRWithImage(imagePath) {
    const dataUrl = await this._readFileAsDataUrl(imagePath)
    const prompt = '请识别图中的信息,返回json格式'
    const resp = await new Promise((resolve, reject) => {
      wx.request({
        url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${this.data.apiKey}`,
          'Content-Type': 'application/json',
        },
        data: {
          model: 'qwen-vl-plus',
          messages: [{
            role: 'user',
            content: [
              { type: 'text', text: prompt },
              { type: 'image_url', image_url: dataUrl },
            ],
          }],
          response_format: { type: 'json_object' },
        },
        timeout: 60000,
        success: (r) => resolve(r),
        fail: (err) => reject(err),
      })
    })
    const choices = resp && resp.data && resp.data.choices
    const content = choices && choices[0] && choices[0].message && choices[0].message.content
    let contentStr = ''
    if (typeof content === 'string') contentStr = content
    else if (Array.isArray(content)) contentStr = content.map(i => (typeof i === 'string' ? i : (i && i.text) || '')).filter(Boolean).join('\n')
    else if (content && typeof content === 'object' && content.text) contentStr = content.text
    else contentStr = JSON.stringify(resp.data || {}, null, 2)

    let parsed = null
    try { parsed = JSON.parse(contentStr) } catch (e) { parsed = null }
    const pretty = parsed ? JSON.stringify(parsed, null, 2) : contentStr
    this.setData({ parsed: parsed || null })
    return pretty
  },


  _afterScan(value) {
    // 直接填充 scanValue，已不再依赖 labelParser
    const parsed = null

    // 输出数量到控制台
    // 保留接口位置，如需后续扩展可在此处理

    // 用解析结果填充表单字段
    var nextForm = Object.assign({}, this.data.form)
    // 不做 labelParser 的字段推断
    this.setData({ form: nextForm })

    // 列表项展示
    const item = {
      lot: this.data.form.lot || '—',
      dateCode: this.data.form.dc || '',
      count: Number(nextForm.count) || 1,
      qty: Number(nextForm.qty) || 0,
      summary: String(value || '').slice(0, 24)
    }
    var items = [item].concat(this.data.items)
    var badges = Object.assign({}, this.data.badges)
    badges.basic = true
    badges.poData = true
    badges.mpn = !!(nextForm.mpn)
    badges.label = items.length
    this.setData({ items, badges })

    if (this.data.form.autoSubmit) {
      this.onSubmitTap()
    }
  },

  // 批量处理多码结果
  _afterScanBatch(values) {
    if (!Array.isArray(values) || values.length === 0) return
    if (values.length === 1) {
      this._afterScan(values[0])
      return
    }
    const now = new Date()
    const fallbackDC = `${now.getFullYear()}${String(now.getMonth()+1).padStart(2,'0')}${String(now.getDate()).padStart(2,'0')}`
    const newItems = values.map(v => {
      const text = String(v || '')
      return {
        lot: this.data.form.lot || '—',
        dateCode: this.data.form.dc || fallbackDC,
        count: Number(this.data.form.count) || 1,
        qty: Number(this.data.form.qty) || 0,
        summary: text.slice(0, 24)
      }
    })
    var items = newItems.concat(this.data.items)
    var badges = Object.assign({}, this.data.badges)
    badges.basic = true
    badges.poData = true
    badges.mpn = !!this.data.form.mpn
    badges.label = items.length
    this.setData({ items, badges })

    if (this.data.form.autoSubmit) {
      this.onSubmitTap()
    }
  },

  // 提交：使用相机拍摄的图片进行 OCR 识别
  async onSubmitTap() {
    if (!this.data.apiKey) {
      wx.showToast({ title: '缺少 API-KEY（请在OCR页保存）', icon: 'none' })
      return
    }
    if (!this.data._latestImagePath) {
      wx.showToast({ title: '请先扫描图片', icon: 'none' })
      return
    }
    
    wx.showLoading({ title: '提交中', mask: true })
    try {
      const pretty = await this._runDashOCRWithImage(this.data._latestImagePath)
      this.setData({ rawText: pretty })

      // 将 OCR 返回的结构填入表单
      let parsed = this.data.parsed
      if (!parsed) {
        try { parsed = JSON.parse(pretty) } catch (_) {
          parsed = this._extractJsonFromText(pretty)
        }
      }
      if (parsed && typeof parsed === 'object') {
        const patch = this._normalizeParsedToForm(parsed) || {}
        var nextForm = Object.assign({}, this.data.form, patch)
        this.setData({ form: nextForm, parsed: parsed })
      }
    } catch (e) {
      wx.showToast({ title: '提交失败', icon: 'none' })
      try {
        const errMsg = (e && (e.errMsg || e.message)) || String(e)
        this.setData({ rawText: `请求失败：${errMsg}` })
        if (/not\s+in\s+domain\s+list/i.test(errMsg) || /url not in domain list/i.test(errMsg)) {
          const tips = '开发调试可在开发者工具-详情-本地设置中勾选"不要校验合法域名、TLS 版本及 HTTPS 证书"；发布或真机请在小程序后台将 https://dashscope.aliyuncs.com 配置到 request 合法域名。'
          wx.showModal({ title: '网络域名未授权', content: tips, showCancel: false })
        }
      } catch (_) {}
    } finally {
      wx.hideLoading()
    }
  },

  onCleanTap() {
    this.setData({ items: [], badges: { basic: false, poData: false, mpn: false, label: 0 }, scanValue: '' })
  },
  onPrintTap() {
    wx.showToast({ title: '打印占位', icon: 'none' })
  },

  onNavOcrScan() {
    wx.navigateTo({ url: '/pages/ocrscan/index' })
  }
})
